{include file="common/head"/}
<style>
    .layui-breadcrumb > * {
        font-size: 18px;
        font-weight: 300;
    }
    .layui-form-pane .layui-form-label{
        width: 160px;
    }
    .layui-upload-img{
        width: 112px;
        height: 96px;
        margin-left: 50px;
    }
</style>
<div style="margin: 15px;" class="fadeInUp animated"  ng-app="hd" ng-controller="ctrl">
    <fieldset class="layui-elem-field layui-field-title">
        <legend>
            <!-- <a href="{:url('list')}"> 素材列表</a> > {$title}  -->
            <span class="layui-breadcrumb">
                <a href="{:url('lists')}"><i class="layui-icon layui-icon-upload-circle"></i> 商品列表</a>
                <a><cite>{$title}</cite></a>
            </span>
        </legend>
       
    </fieldset>
    <div class="layui-tab" lay-filter="filter">
        <ul class="layui-tab-title">
            <li class="layui-this" lay-id="one">基础信息</li>
            <li lay-id="two">详情页封面图</li>
            <li lay-id="three">规格</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show" >
                <form class="layui-form layui-form-pane">
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品名称</label>
                        <div class="layui-input-4">
                            <input type="text" name="name" lay-verify="required" value="{{field.name}}" placeholder="{:lang('pleaseEnter')}商品名称" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">货号/编码</label>
                        <div class="layui-input-4">
                            <input type="text" name="code" value="{{field.code}}" placeholder="{:lang('pleaseEnter')}货号/编码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">列表小图</label>
                        <input type="hidden" name="pic" id="pic" value="{{field.pic}}">
                        <div class="layui-input-block">
                            <div class="layui-upload">
                                <button type="button" class="layui-btn layui-btn-primary" id="adBtn"><i
                                        class="icon icon-upload3"></i>点击上传（宽112px, 高96px）</button>
                                <div class="layui-upload-list">
                                    <img class="layui-upload-img" id="adPic">
                                    <p id="demoText"></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">加盟商商品分类</label>
                        <div class="layui-input-4">
                            <select name="agent_product_id" lay-verify="" lay-filter="agent_product_id">
                                <option value="0">请选择商品分类</option>
                                {volist name="agent_goods_category" id="vo"}
                                <option value="{$key}" {if $baseInfo.agent_product_id}{if $baseInfo.agent_product_id==$key}selected{/if}{/if}>{$vo}</option>
                                {/volist}
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">品牌</label>
                        <div class="layui-input-4">
                            <select name="brand_id" lay-verify="required" lay-filter="brand_id" lay-verify="required">
                                <option value="0">请选择品牌</option>
                                {volist name="brand" id="vo"}
                                <option value="{$vo.id}" {if $baseInfo.brand_id}{if $baseInfo.brand_id == $vo.id}selected{/if}{/if}>{$vo.title}</option>
                                {/volist}
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">普通用户商品分类</label>
                        <div class="layui-input-inline">
                            <select name="category_one" id="category_one" lay-verify="" lay-filter="category_one" >
                                <option value="">请选择一级分类</option>
                                {volist name="category_one_list" id="vo"}
                                <option value="{$vo.id}" {if $baseInfo.category_one}{if $baseInfo.category_one == $vo.id}selected{/if}{/if}>{$vo.title}</option>
                                {/volist}
                            </select>
                        </div>
                        <!-- <div class="layui-input-inline">
                            <select name="category_two" id="category_two" lay-verify=""  >
                                <option value="">请选择二级级分类</option>
                                {if $category_two_list}
                                {volist name="category_two_list" id="vo"}
                                <option value="{$vo.id}" {if $baseInfo.category_two}{if $baseInfo.category_two == $vo.id}selected{/if}{/if}>{$vo.title}</option>
                                {/volist}
                                {/if}
                            </select>
                        </div> -->
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">售价</label>
                        <div class="layui-input-4">
                            <input type="text" name="sale_price" lay-verify="required" value="{{field.sale_price}}" placeholder="{:lang('pleaseEnter')}售价" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">原价</label>
                        <div class="layui-input-4">
                            <input type="text" name="original_price"  value="{{field.original_price}}" placeholder="{:lang('pleaseEnter')}原价" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">库存</label>
                        <div class="layui-input-4">
                            <input type="text" name="stock" value="{{field.stock}}" placeholder="{:lang('pleaseEnter')}库存" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">上/下架</label>
                            <div class="layui-input-block">
                                <input type="radio" name="status" ng-model="field.status" ng-checked="field.status==1" ng-value="1" title="上架">
                                <input type="radio" name="status" ng-model="field.status" ng-checked="field.status==2" ng-value="2" title="下架">
                            </div>
                        </div>
                    </div>
                    <!-- <div class="layui-form-item">
                        <label class="layui-form-label">生产日期</label>
                        <div class="layui-input-4">
                            <input type="text" name="make_date" id="make_date" value="{{field.make_date}}" placeholder="{:lang('pleaseEnter')}生产日期" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">有效期</label>
                        <div class="layui-input-4">
                            <input type="text" name="life_date" id="life_date" value="{{field.life_date}}" placeholder="{:lang('pleaseEnter')}有效期" class="layui-input">
                        </div>
                    </div> -->
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">商品描述</label>
                        <div class="layui-input-block">
                            <textarea name="desc" id="desc" class="layui-textarea" lay-verify="required">{{field.desc}}</textarea>
                        </div>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">商品内容</label>
                        <div class="layui-input-block">
                            <textarea name="content" id="content" class="layui-textarea" lay-verify="required">{{field.content}}</textarea>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">排序</label>
                        <div class="layui-input-4">
                            <input type="text" name="sort" value="{{field.sort}}" placeholder="{:lang('pleaseEnter')}排序编号" class="layui-input">
                        </div>
                    </div>
                    <input type="hidden" name="id" value="{{field.id}}" />
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
                            <a href="{:url('lists')}" class="layui-btn layui-btn-primary">返回</a>
                        </div>
                    </div>
                </form>
            </div>
            <div class="layui-tab-item"> <!-- 图片 -->
                {if $pic}
                <fieldset class="layui-elem-field">
                    <legend>当前商品图片</legend>
                    <div class="layui-field-box" style="text-align: center;width: 50%;">
                        <table class="layui-table">
                            <colgroup>
                                <col width="150">
                                <col width="100">
                            </colgroup>
                            <thead><tr><th style="text-align: center">缩略图</th><th style="text-align: center">操作</th></tr></thead>
                            <tbody id="two_tbody">
                            {foreach $pic as $key=>$value}
                            <tr><td><img src="{$value['pic']}"></td><td><button class="layui-btn layui-btn-xs layui-btn-danger base-pic-delete" data-imgid="{$value['id']}">删除</button></td></tr>
                            {/foreach}
                            </tbody>
                        </table>
                    </div>
                </fieldset>
                {/if}
                <fieldset class="layui-elem-field">
                    <legend>添加图片</legend>
                    <div class="layui-field-box">
                        <div class="layui-upload">
                            <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件（宽380px 高442px）</button>
                            <button type="button" class="layui-btn" id="testListAction">开始上传</button>
                            <div class="layui-upload-list">
                                <table class="layui-table">
                                    <thead>
                                    <tr><th>文件名</th>
                                        <th>大小</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr></thead>
                                    <tbody id="demoList"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </fieldset>
            </div>
            <div class="layui-tab-item"><!-- 规格 -->
                <div class="demoTable">
                    <div class="layui-block">
                        <label class="layui-form-label">规格/SKU</label>
                        <div class="layui-input-2">
                            <input type="text" placeholder="{:lang('pleaseEnter')}规格名称" class="layui-input add_gg_name">
                        </div>
                        <button class="layui-btn" id="add_gg">新增</button>
                    </div>
                    <hr/>
                    <div id="sku_sku"><!-- sku数据 -->
                    {if $sku_data}
                        {foreach $sku_data as $k1=>$v1}
                        <blockquote class="layui-elem-quote">
                            <div class="layui-block">
                                  <label class="layui-form-label">{$v1.key}</label>
                                    <div class="layui-input-2"><input type="text" class="layui-input"></div>
                                    <button class="layui-btn add_sku" data-name="{$v1.key}">添加</button>
                                    <button class="layui-btn layui-btn-danger del_sku">移除</button>
                                    <div class="layui-inline str_sku" data-str="{$v1.desc}" style="margin-left: 50px;">
                                        {foreach $v1.val as $k2=>$v2}
                                        <button class="layui-btn layui-btn-sm layui-btn-normal str_remove" data-remove="{$v2}" title="移除"> {$v2} <i class="layui-icon layui-icon-close" style="color: #FFF;font-size: 13px!important"></i></button>
                                        {/foreach}
                                    </div>
                            </div>
                         </blockquote>
                        {/foreach}
                    {/if}
                    </div>
                    <div style="clear: both;"></div>
                </div>
                <div id="table_sku"> <!-- sku表格 -->
                {if $sku_html}
                    {$sku_html|raw}
                {/if}
                </div>
                <button type="button" class="layui-btn" style="margin-top: 20px;" id="save_sku">保存</button>
            </div>
        </div>
    </div>
</div>
{include file="common/foot"/}
<script src="/static/common/js/angular.min.js"></script>
<script src="/static/common/js/jquery.2.1.1.min.js"></script>
<script charset="utf-8" src="/static/ueditor/ueditor.config.js"></script>
<script charset="utf-8" src="/static/ueditor/ueditor.all.js"></script>
<script>
    var ue = UE.getEditor('content',{
        initialFrameWidth:1000,
        initialFrameHeight:500,
        autoHeightEnabled:false,
        // maximumWords:30000
    });
</script>
<script>
    var baseInfoId=0;
    var m = angular.module('hd',[]);
    m.controller('ctrl',['$scope',function($scope) {
        $scope.field = '{$info|raw}'!='null'?{$info|raw}:{id:'',title:'',sort:50,pic:''};
        baseInfoId = $scope.field.id;
        layui.use(['form', 'layer','upload','laydate','element','table'], function () {
            var form = layui.form, $ = layui.jquery, upload = layui.upload,laydate = layui.laydate, element = layui.element, table = layui.table;
            // sku 新增
            // 第一步  新增规格
            var gg_data = "";
            var gg_div_num = 0;
            $("body").on('click','#add_gg',function () {
                gg_div_num = $(".layui-elem-quote").length;
                if(gg_div_num >= 1){
                    layer.msg('目前只支持创建一种规格/SKU', { time: 1800, icon: 2 });
                    return false;
                }
                if(baseInfoId){
                    var name = $('.add_gg_name').val();
                    if(name){
                        gg_data = gg_data == "" ? gg_data+=name : gg_data+=','+name;
                        var html = '<blockquote class="layui-elem-quote">\n' +
                            '                            <div class="layui-block">\n' +
                            '                                <label class="layui-form-label">'+name+'</label>\n' +
                            '                                <div class="layui-input-2"><input type="text" class="layui-input"></div>\n' +
                            '                                <button class="layui-btn add_sku" data-name="'+name+'">添加</button>\n' +
                            '                                <button class="layui-btn layui-btn-danger del_sku">移除</button>\n' +
                            '                                <div class="layui-inline str_sku" data-str="" style="margin-left: 50px;"></div>\n' +
                            '                            </div>\n' +
                            '                        </blockquote>';
                        $('#sku_sku').append(html);
                        $('.add_gg_name').val("");
                    }else{
                        layer.msg('请输入规格', {time: 1800, icon: 2});
                    }
                }else{
                    layer.msg('请先填写基础信息', {time: 1800, icon: 2});
                }
            });
            // 第一步 移除规格
            $("body").on('click','.del_sku',function () {
                $(this).parent().parent().remove();
                take();
            });
            // 第二步 新增规格具体值
            $("body").on('click','.add_sku',function () {
                var str = $(this).parent().find('input').val();
                str = str.replace(/,/, " ")
                str = str.replace(/-/, " ")
                str = str.replace(/#/, " ")
                var sku_name = $(this).data('name');
                if(str){
                    // 先增加str
                    var str_html = '<button class="layui-btn layui-btn-sm layui-btn-normal str_remove" data-remove="'+str+'" title="移除"> '+str+' <i class="layui-icon layui-icon-close" style="color: #FFF;font-size: 13px!important"></i></button>';
                    $(this).parent().find('.str_sku').append(str_html);console.log(str_html);
                    $(this).parent().find('input').val("");
                    // 处理表格
                    var str_data = $(this).parent().find('.str_sku').data('str');
                    str_data = str_data == "" ? str_data+=str : str_data+=','+str;
                    $(this).parent().find('.str_sku').data('str',str_data);
                    take();
                }else{
                    layer.msg('请输入'+sku_name, {time: 1800, icon: 2});
                }
            });
            // 第二步 移除规格具体值
            $("body").on('click','.str_remove',function () {
                var parent = $(this).parent().data('str');
                var value = $(this).data('remove');
                var obj = $(this);
                var loading = layer.load(1, {shade: [0.1, '#fff']});
                $.post("takeSkuValue", {parent:parent,value:value}, function (res) {
                    layer.close(loading);
                    obj.parent().data('str',res);
                    obj.remove();
                    take();
                });
            });
            // 保存规格
            $("body").on('click','#save_sku',function () {
                if(baseInfoId){
                    var price_data = "";
                    var agent_price_data = "";
                    var stock_data = "";
                    $('#table_sku table tbody tr').each(function (i) {
                        var sku_price = $(this).find('.sku_price').val();
                        var sku_agent_price = $(this).find('.sku_agent_price').val();
                        var sku_stock = $(this).find('.sku_stock').val();
                        if(sku_price){
                            price_data += i == 0 ? sku_price : ','+sku_price;
                        }else{
                            layer.msg('请填写售价', {time: 1800, icon: 2});
                            return false;
                        }
                        if(sku_agent_price){
                            agent_price_data += i==0? sku_agent_price : ','+ sku_agent_price;
                        }
                        if(sku_stock){
                            stock_data += i == 0 ? sku_stock : ','+sku_stock;
                        }else{
                            layer.msg('请填写库存', {time: 1800, icon: 2});
                            return false;
                        }
                    });
                    if(price_data && stock_data){
                        var loading = layer.load(1, {shade: [0.1, '#fff']});
                        $.post("saveSku", {id:$scope.field.id,price_data:price_data,agent_price_data:agent_price_data,stock_data:stock_data}, function (res) {
                            layer.close(loading);
                            if (res.code > 0) {
                                layer.msg(res.msg, {time: 1800, icon: 1});
                            } else {
                                layer.msg(res.msg, {time: 1800, icon: 2});
                            }
                        });
                    }else{
                        layer.msg('请填写规格/SKU', {time: 1800, icon: 2});
                    }

                }else{
                    layer.msg('请先填写基础信息', {time: 1800, icon: 2});
                }
            });
            // 生成sku表格
            function take(){
                var sku_key = "";
                var sku_data = "";
                $('#sku_sku .add_sku').each(function (i) {
                    sku_key = i == 0 ? sku_key+=$(this).data('name') : sku_key+=','+$(this).data('name');
                });
                $('#sku_sku .str_sku').each(function (i) {
                    sku_data = i == 0 ? sku_data+=$(this).data('str') : sku_data+='-'+$(this).data('str');
                });
                console.log(sku_key);
                console.log(sku_data);
                var loading = layer.load(1, {shade: [0.1, '#fff']});
                $.post("getSku", {id:$scope.field.id,name:sku_key,str:sku_data}, function (res) {
                    layer.close(loading);
                    if (res.code > 0) {
                        $('#table_sku').html(res.data);
                    } else {
                        layer.msg(res.msg, {time: 1800, icon: 2});
                    }
                });
            }

            // 切换 Tab 
            element.on('tab(filter)', function(data){
                if(data.index > 0){
                    if(baseInfoId == 0){
                        layer.msg('请先保存基本信息1', { time: 1800, icon: 2 });
                        element.tabChange('filter', 'one');
                    }else{
                        return false;
                    }
                }
            });
            if($scope.field.pic){
                adPic.src = $scope.field.pic;
            }
            laydate.render({
                elem: '#make_date'
            });
            laydate.render({
                elem: '#life_date'
            });
            // 第一步  保存基本信息
            form.on('submit(submit)', function (data) {
                // 提交到方法 默认为本身
                data.field.id = $scope.field.id;
                data.field.content = ue.getContent();
                var loading = layer.load(1, {shade: [0.1, '#fff']});
                $.post("", data.field, function (res) {
                    layer.close(loading);
                    if (res.code > 0) {
                        layer.msg(res.msg, {time: 1800, icon: 1});
                        form.render();
                        baseInfoId = res.id
                        element.tabChange('filter', 'two');
                    } else {
                        layer.msg(res.msg, {time: 1800, icon: 2});
                    }
                });
            });
            form.on('select(brand_id)', function(data) {
                var id = data.value;
                var loading = layer.load(1, {shade: [0.1, '#fff']});
                $.get("{:url('getCategory')}?id=" + id, function (data) {
                    layer.close(loading);
                    var html='<option value="">请选择一级分类</option>';
                    $.each(data, function (i, value) {
                        html += '<option value="'+value.id+'">'+value.title+'</option>';
                    });
                    console.log(html);
                    $('#category_one').html(html);
                    form.render()
                });
            });
            form.on('select(category_one)', function(data) {
                var id = data.value;
                var loading = layer.load(1, {shade: [0.1, '#fff']});
                $.get("{:url('getCategory')}?id=" + id, function (data) {
                    layer.close(loading);
                    var html='<option value="">请选择二级分类</option>';
                    $.each(data, function (i, value) {
                        html += '<option value="'+value.id+'">'+value.title+'</option>';
                    });
                    console.log(html);
                    $('#category_two').html(html);
                    form.render()
                });
            });
            // 图片删除
            $("body").on('click','.base-pic-delete',function () {
                var id = $(this).data('imgid');
                var obj = $(this);
                var loading = layer.load(1, {shade: [0.1, '#fff']});
                $.post("imgDel", {id:id}, function (res) {
                    layer.close(loading);
                    if (res.code > 0) {
                        obj.parent().parent().remove();
                        layer.msg(res.msg, {time: 1800, icon: 1});
                    } else {
                        layer.msg(res.msg, {time: 1800, icon: 2});
                    }
                });
            });
            //多文件列表示例
            var demoListView = $('#demoList')
                ,uploadListIns = upload.render({
                elem: '#testList'
                ,url: ''
                ,accept: 'file'
                ,multiple: true
                ,auto: false
                ,bindAction: '#testListAction'
                ,before: function(obj){
                    this.url = '{:url("Goods/uploads")}?id=' + + baseInfoId
                }
                ,choose: function(obj){
                    var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                    //读取本地文件
                    obj.preview(function(index, file, result){
                        var tr = $(['<tr id="upload-'+ index +'">'
                            ,'<td>'+ file.name +'</td>'
                            ,'<td>'+ (file.size/1024).toFixed(1) +'kb</td>'
                            ,'<td>等待上传</td>'
                            ,'<td>'
                            ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                            ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                            ,'</td>'
                            ,'</tr>'].join(''));

                        //单个重传
                        tr.find('.demo-reload').on('click', function(){
                            obj.upload(index, file);
                        });

                        //删除
                        tr.find('.demo-delete').on('click', function(){
                            delete files[index]; //删除对应的文件
                            tr.remove();
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        });

                        demoListView.append(tr);
                    });
                }
                ,done: function(res, index, upload){
                    if(res.files.file){ //上传成功
                        var tr = demoListView.find('tr#upload-'+ index)
                            ,tds = tr.children();
                        tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                        tds.eq(3).html(''); //清空操作
                        var str = '<tr><td><img src="'+res.files.file+'"></td><td><button class="layui-btn layui-btn-xs layui-btn-danger base-pic-delete" data-imgid="'+res.files.id+'">删除</button></td></tr>';
                        $("#two_tbody").append(str);
                        return delete this.files[index]; //删除文件队列已经上传成功的文件
                    }
                    this.error(index, upload);
                }
                ,error: function(index, upload){
                    var tr = demoListView.find('tr#upload-'+ index)
                        ,tds = tr.children();
                    tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                    tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
                }
            });

             //普通图片上传
            var uploadInst = upload.render({
                elem: '#adBtn'
                , url: '{:url("UpFiles/upload")}'
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#adPic').attr('src', result); //图片链接（base64）
                    });
                },
                done: function (res) {
                    if (res.code > 0) {
                        $('#pic').val(res.url);
                    } else {
                        //如果上传失败
                        return layer.msg('上传失败');
                    }
                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
            });

        });
    }]);
</script>